package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * C端-用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.构造实例对象orders、order_detail,根据addressBookId去查询地址数据
        Orders orders = new Orders();  //订单表对象
        List<OrderDetail> orderDetailList = new ArrayList<>();  //订单明细表集合对象

        AddressBook addressBook = new AddressBook();  //地址簿对象
        ShoppingCart shoppingCart = new ShoppingCart();  //购物车对象
        //返回数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();  //订单提交对象


        //2.属性对拷,将传来的数据拷贝到订单表对象，并剔除id主键
        BeanUtils.copyProperties(ordersSubmitDTO, orders, "id");

        //3.查询user表，获取当前下单人信息,设置下单人id和下单人姓名
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getUserById(userId);
        orders.setUserId(userId);
        orders.setUserName(user.getName());


        //4.查询address_book表，获取收货人信息，设置收件人收件人手机号和地址、姓名
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        addressBook.setId(addressBookId);
        addressBook = addressBookMapper.getAddressBookById(addressBook);

        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        //5.设置订单表的订单号、订单状态、下单时间、
        //String s = UUID.randomUUID().toString();

        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        // 定义格式化模式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 格式化为字符串
        String formatted = now.format(formatter).toString();
        System.out.println("格式化后的日期时间: " + formatted);


        orders.setNumber(formatted + (String.valueOf(System.currentTimeMillis())));//设置订单号
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);//支付状态

        //6.插入订单表信息
        ordersMapper.insert(orders);

        //7.将购物车中的数据拷贝给订单明细表
        //7.1 根据用户id去查询购物车数据
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        //7.2 遍历购物车中的数据
        shoppingCarts.forEach(shoppingCart1 -> {
            //订单明细表对象
            OrderDetail orderDetail = new OrderDetail();
            //将购物车中的数据拷贝给订单明细表，剔除id主键
            BeanUtils.copyProperties(shoppingCart1, orderDetail, "id");
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);  //添加进集合中
        });
//        BeanUtils.copyProperties(shoppingCarts, orderDetailList, "id");

        //8.清空购物车
        shoppingCartMapper.clean(userId);

        //9.批量插入订单明细表信息
        orderDetailMapper.insertBatch(orderDetailList);


        //10.返回数据
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getUserById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
        /////////////////////////////////////////////////////////////////////////////////////////////////////////
        //模拟支付成功，修改订单状态
        //业务处理，修改订单状态、来单提醒
        paySuccess(ordersPaymentDTO.getOrderNumber());
        //返回一个空对象
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        log.info("--------支付成功，修改订单状态：{}--------", outTradeNo);

        //当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo,userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //通过webSocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 1); //1 表示来单提醒 2表示客户催单
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        log.info("--------修改订单状态成功：{}--------", json);
    }

    @Override
    public PageResult historyOrders(Integer pageSize, Integer page, Integer status) {
        //1.调用分页插件，设置分页参数
        PageHelper.startPage(page, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        //分页查询
        Page<Orders> pageQuery = ordersMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (pageQuery != null && pageQuery.getTotal() > 0) {
            pageQuery.forEach(orders -> {
                Long orderId = orders.getId();//订单id

                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);

                orderVOList.add(orderVO);
            });

        }
        return new PageResult(pageQuery.getTotal(), orderVOList);
    }

    /**
     * C端-根据订单id查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetail(Long id) {
        //实例化一个对象
        OrderVO orderVO = new OrderVO();
        List<OrderDetail> orderDetailList = new ArrayList<>();
//        OrderDetail orderDetail = new OrderDetail();
//        orderDetail.setOrderId(id);


        //查询订单表
        Orders orders = ordersMapper.selectById(id);

        //查询订单详情表
        orderDetailList = orderDetailMapper.getByOrderId(id);

        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);


        return orderVO;
    }

    /**
     * C端-根据订单id取消订单
     *
     * @param id
     */
    @Override
    @Transactional //同时操作两张及以上的表时需要开启事务
    public void cancelOrderById(Long id) {
        //1.删除订单
        ordersMapper.cancelOrderById(id);

        //2.删除订单详情
        orderDetailMapper.deleteOrderDetailByOrderId(id);
    }

    /**
     * C端-根据订单id再来一单
     *
     * @param id
     */
    @Override
    @Transactional //同时操作两张及以上的表时需要开启事务
    public void repetitionByOrderId(Long id) {
        //再来一单就是将原订单中的商品重新加入到购物车中
        Long userId = BaseContext.getCurrentId();

        //根据订单id查询订单详情表
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //遍历查询出来的orderDetailList数据,创建一个购物车列表
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");

            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 管理端-订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //1.调用分页插件进行分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //1.1分页查询结果
        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);
        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        //构建分页结果
        return new PageResult(page.getTotal(), orderVOList);
    }


    public List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        //判断集合里面的数据不为空
        if (!CollectionUtils.isEmpty(ordersList)) {
            ordersList.forEach(orders -> {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();

                BeanUtils.copyProperties(orders, orderVO);

                //查询订单菜品信息
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            });

        }
        return orderVOList;
    }

    public String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(orderDetail -> {
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());
        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 管理端-各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO selectOrders() {
        //1.根据状态查询订单列表
        //状态为待派送
        Integer confirmed = ordersMapper.countStatus(Orders.CONFIRMED);
        //状态为派送中
        Integer deliveryInProgress = ordersMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        //状态为待接单
        Integer toBeConfirmed = ordersMapper.countStatus(Orders.TO_BE_CONFIRMED);

        //2.创建一个实例化OrderStatisticsVO对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setConfirmed(confirmed);

        return orderStatisticsVO;
    }

    /**
     * 管理端-拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //根据id查询订单
        Orders order = ordersMapper.selectById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (order == null || order.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //判断订单是否支付
        Integer payStatus = order.getPayStatus();
        Orders orders = new Orders();
        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = null;
//            try {
//                refund = weChatPayUtil.refund(order.getNumber(), order.getNumber(), new BigDecimal(0.01), new BigDecimal(0.01));
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//            log.info("申请退款：{}", refund);

            // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
            orders.setId(order.getId());
            orders.setStatus(Orders.CANCELLED);
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setCancelTime(LocalDateTime.now());
        }
        ordersMapper.update(orders);
    }

    /**
     * 管理端-接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //1.根据id查询订单表
        Orders order = ordersMapper.selectById(ordersConfirmDTO.getId());

        //2.判断是否已支付
        // 订单只有存在且状态为2（待接单）才可以接单
        if (order == null || order.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //3.修改订单状态为已接单
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        //2.更新订单表
        ordersMapper.update(orders);
    }

    /**
     * 管理端-取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //根据id查询订单
        Orders order = ordersMapper.selectById(ordersCancelDTO.getId());

        //2.判断顾客是否已付款
        if (order.getPayStatus() == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = null;
//            try {
//                refund = weChatPayUtil.refund(order.getNumber(), order.getNumber(), new BigDecimal(0.01), new BigDecimal(0.01));
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//            log.info("申请退款：{}", refund);
        }
        // 取消单需要退款，根据订单id更新订单状态、取消订单原因、取消时间
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 管理端-派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 根据id查询订单
        Orders order = ordersMapper.selectById(id);

        // 校验订单是否存在，并且状态为3
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 更新订单状态,状态转为派送中
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .deliveryStatus(1)
                .build();

        ordersMapper.update(orders);
    }


    /**
     * 管理端-完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //1.根据id查询订单
        Orders order = ordersMapper.selectById(id);

        //2.校验订单是否存在，并且状态为4
        if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //3.更新订单状态,状态转为完成
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = ordersMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        log.info("有用户催单啦：{}", map);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
